#!/usr/bin/python
# # -*- encoding:utf-8 -*-
import smtplib
from email.mime.text import MIMEText
from email.utils import formataddr


class MailUtil(object):
    senderMailAddr = '728067113@qq.com'
    senderAccount = '728067113@qq.com'
    senderNickname = 'Jerry.Franklyn'
    senderMailPassword = 'flowdoarmhfmbbce'
    senderMailServerPort = 465  # Port
    senderMailServerAddr = 'smtp.qq.com'  # Host

    def __init__(self, reciever, Subject):
        self.reciever = reciever
        self.Subject = Subject

    def sendHtml(self, htmlBodyStr):
        exec_result = True
        try:
            # 设置文本内容；格式如plain、html
            msg = MIMEText(htmlBodyStr, 'html', 'utf-8')
            msg['From'] = formataddr([self.senderNickname, self.senderMailAddr])  # 发件人邮箱账号
            msg['To'] = self.reciever  # 收件人邮箱账号
            msg['Subject'] = self.Subject  # 邮件主题
            self.__sendMail_withSSL(msg)
        except BaseException as e:  # 如果发生异常，则返回False
            print(e)
            exec_result = False
        return exec_result

    def __sendMail_NoSSL(self, msg):
        server = smtplib.SMTP(self.senderMailServerAddr, self.senderMailServerPort)  # 发件人邮箱中的SMTP服务器，端口是25
        server.login(self.senderAccount, self.senderMailPassword)  # 括号中对应的是发件人邮箱账号、邮箱密码
        server.sendmail(self.senderMailAddr, [self.reciever, ], msg.as_string())  # 括号中对应的是发件人邮箱账号、收件人邮箱账号、发送邮件
        server.quit()  # 关闭连接

    def __sendMail_withSSL(self, msg):
        server = smtplib.SMTP_SSL(self.senderMailServerAddr, self.senderMailServerPort)  # 发件人邮箱中的SMTP服务器，端口是25
        server.login(self.senderAccount, self.senderMailPassword)  # 括号中对应的是发件人邮箱账号、邮箱密码
        server.sendmail(self.senderMailAddr, [self.reciever, ], msg.as_string())  # 括号中对应的是发件人邮箱账号、收件人邮箱账号、发送邮件
        server.quit()  # 关闭连接
